import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import { routes } from "./routes";

// 声明全局变量类型
declare global {
  interface Window {
    __MICRO_APP_ENVIRONMENT__?: boolean;
    __MICRO_APP_NAME__?: string;
    microApp?: any;
  }
}

// 判断是否在微前端环境中
const isMicroApp = window.__MICRO_APP_ENVIRONMENT__ || false;

// 创建路由实例 - 在微前端环境中使用空字符串作为基础路径
const router = createRouter({
  history: createWebHistory(isMicroApp ? "/appOrder" : ""),
  routes: routes as unknown as RouteRecordRaw[],
});

// 添加路由守卫，用于调试
router.beforeEach((to, from, next) => {
  console.log("子应用路由守卫触发:", from.path, "->", to.path);
  next();
});

// 添加路由后置钩子，用于通知主应用
router.afterEach((to) => {
  console.log("子应用路由已更新到:", to.path);

  // 在微前端环境中，向主应用发送路由变化通知
  if (window.__MICRO_APP_ENVIRONMENT__ && window.microApp) {
    window.microApp.dispatch({
      type: "routeChange",
      path: to.path,
      fullPath: to.fullPath,
    });
  }
});

export default router;
